<template>
  <view class="bg-white">
    <nav-bar title="编辑会员信息" color="white" bg-color="#111827" show-back></nav-bar>
    <view class="content p-20rpx">
      <u-row gutter="10rpx">
        <u-col span="9" custom-style="">
          <u-form ref="refRecharge" :model="formData" :rules="formRules" label-width="5rem" label-position="top">
            <view class="flex justify-between">
              <u-form-item label="会员姓名:" prop="customerName" required>
                <view class="my-5rpx w-full">
                  <u-input v-model="formData.customerName"></u-input>
                </view>
              </u-form-item>
              <u-form-item label="手机号码:">
                <view class="my-5rpx w-full">
                  <u-input v-model="formData.customerPhone" disabled font-size="10rpx"></u-input>
                </view>
              </u-form-item>
              <u-form-item label="身份证号:">
                <view class="my-5rpx w-full">
                  <u-input v-model="formData.cardId" disabled font-size="10rpx"></u-input>
                </view>
              </u-form-item>
            </view>
            <view class="flex justify-between">
              <u-form-item label="客户类型:" prop="deposit">
                <view class="w-full">
                  <u-input v-model="formData.customerTypeName" disabled></u-input>
                </view>
              </u-form-item>
              <u-form-item label="家庭地址:" prop="deposit">
                <view class="w-full">
                  <u-input v-model="formData.homeAddress" @click="openSheet"></u-input>
                </view>
              </u-form-item>
              <u-form-item label="会员卡级别:">
                <view class="w-full">
                  <u-input v-model="accountInfo.membershipLevelName" disabled font-size="10rpx"></u-input>
                </view>
              </u-form-item>
            </view>
            <view class="flex justify-between">
              <u-form-item label="物理卡号:" prop="physicalCardNumber">
                <view class="w-full">
                  <!-- <u-search
                    shape="square"
                    placeholder="读取卡号"
                    v-model="formData.physicalCardNumber"
                    search-icon-size="15rpx"
                    action-text="读取"
                    @custom="startReadCard"
                  ></u-search> -->
                  <u-input v-model="formData.physicalCardNumber" disabled></u-input>
                </view>
              </u-form-item>
              <u-form-item label="逻辑卡号:" prop="logicalCardNumber">
                <view class="w-full">
                  <u-input v-model="formData.logicalCardNumber" type="number" font-size="10rpx" disabled></u-input>
                </view>
              </u-form-item>
              <u-form-item label="办卡类型:" prop="membershipCardType">
                <view class="w-full">
                  <u-input disabled v-model="formData.membershipCardType" font-size="10rpx"></u-input>
                </view>
              </u-form-item>
            </view> </u-form
        ></u-col>
        <u-col span="3">
          <view class="ml-10rpx">
            <view>
              <text class="text-base text-gray-800">照片上传</text>
            </view>
            <view
              @click="openCamera"
              class="w-120rpx h-120rpx my-5rpx rounded-md flex justify-center items-center"
              style="border: 1px solid lightgrey"
            >
              <!-- 上传照片 -->
              <u-image
                v-if="formData.faceUrl"
                :src="formData.faceUrl || '/static/images/icons/icon-face-rec.svg'"
                mode="aspectFill"
                width="110rpx"
                height="110rpx"
              ></u-image>
              <view v-else class="w-110rpx h-110rpx flex flex-col justify-center items-center">
                <u-image
                  src="/static/images/icons/icon-face-rec.svg"
                  mode="aspectFill"
                  width="50rpx"
                  height="50rpx"
                ></u-image>
                <text class="mt-10rpx font-bold" style="color: #1684fc">开始采集</text>
              </view>
            </view>
          </view>
        </u-col>
      </u-row>
      <view class="flex justify-end w-fit m-auto mt-20rpx confirm-btn">
        <u-button type="primary" size="large" @click="confirm">保存</u-button>
      </view>
    </view>

    <nfc-popup ref="refNfcPopup" />

    <!-- 通知结果弹窗 -->
    <resultPopup ref="refResultPopup" :show-icon="true"> </resultPopup>

    <!-- 提示采集注意事项 -->
    <resultPopup ref="refTipsPopup" :show-icon="false">
      <template #default>
        <view class="flex flex-col justify-center items-center">
          <u-image src="/static/images/icons/scan-face.png" mode="aspectFill" width="110rpx" height="110rpx"></u-image>
          <text class="mt-10rpx font-bold text-base">状态：{{ formData.faceUrl ? "已采集" : "未采集" }}</text>
          <view class="w-200rpx text-base mt-20rpx text-slate-600">
            <u-grid :border="false" col="2">
              <u-grid-item v-for="(title, listIndex) in faceTipsList" :key="listIndex">
                <view class="flex justify-start items-center py-5rpx">
                  <text class="mr-10rpx font-bold" style="color: #1684fc">{{ listIndex + 1 }}</text>
                  <text class="grid-text">{{ title }}</text>
                </view>
              </u-grid-item>
            </u-grid>
          </view>
        </view>
      </template>
      <template #confirm>
        <view class="bg-blue-500 text-white px-20rpx py-8rpx rounded-lg" @click="startScanFace">
          <text class="btns-item-txt"> 开始采集 </text>
        </view>
      </template>
    </resultPopup>

        <!-- 地址选择器 -->
        <kui-tree-picker
      ref="kuiTreepPicker"
      @chargeValue="onSubmitPicker"
      :treeData="treePickeConfig.treeData"
      :lazyFun="lazyFun"
      class="kui-treep-picker"
    >
    </kui-tree-picker>
  </view>
</template>
<script setup>
import { accountEdit, customerEdit, updateHeadPortrait, uploadFile } from "@/api";
import { onMounted, reactive, ref } from "vue";
import { getDetailsByCustomerId } from "./utils";
import { onLoad } from "@dcloudio/uni-app";
import resultPopup from "@/components/common-popup/result-popup.vue";
import { asyncExecFunction } from "@/king-components/js/KingonPlus";
import { getDeviceConfig } from "@/common/devices-config";
import { closeSubScreen, openSubScreen, openSubScreenByParams } from "@/utils/sceeenUtils";

const refResultPopup = ref();

const accountInfo = ref({});
const cardInfo = ref({});
const customerInfo = ref({});
const getPageData = async () => {
  console.log("getPageData:>", pagePam);
  try {
    const result = await getDetailsByCustomerId(pagePam.id);
    accountInfo.value = result.accountInfo;
    cardInfo.value = result.cardInfo;
    customerInfo.value = result.customerInfo;

    const temp = {
      /** 老人名称 */
      customerName: customerInfo.value.customerName,

      /** 会员等级名称 */
      membershipLevelName: customerInfo.value.membershipLevelName,
      /** 手机号 */
      customerPhone: customerInfo.value.customerPhone,
      /** 身份证号 */
      cardId: customerInfo.value.cardId,
      /** 家庭住址 */
      homeAddress: customerInfo.value.homeAddress,
      /** 物理卡号 */
      physicalCardNumber: cardInfo.value.physicalCardNumber,
      /** 逻辑卡号 */
      logicalCardNumber: cardInfo.value.logicalCardNumber,
      /** 客户类型 */
      customerTypeName: customerInfo.value.customerTypeName,
      /** 照片地址 */
      faceUrl: customerInfo.value.faceUrl,
      /** 办卡类型 */
      membershipCardType: cardInfo.value.membershipCardType == 2 ? "套餐办卡" : "普通办卡",
    };
    Object.assign(formData, temp);
  } catch (error) {
    console.error(error);
  }
};

// 页面传递的参数
const pagePam = {
  id: "",
};

onLoad((e) => {
  console.log("onLoad:>", e);
  if (e.id) pagePam.id = e.id;
});

onMounted(getPageData);

// 表单
const formData = reactive({
  /**	账户名称 */
  accountName: "",
  /** 老人名称 */
  customerName: "",
  /** 会员等级名称 */
  membershipLevelName: "",
  /** 手机号 */
  customerPhone: "",
  /** 身份证号 */
  cardId: "",
  /** 家庭住址 */
  homeAddress: "",
  /** 物理卡号 */
  physicalCardNumber: "",
  /** 逻辑卡号 */
  logicalCardNumber: "",
  /** 客户类型 */
  customerTypeName: "",
  /** 照片地址 */
  faceUrl: "",
  /** 办卡类型 */
  membershipCardType: "",
});
// 表单规则
const formRules = {
  customerName: {
    type: "string",
    required: true,
    message: "请填输入会员名称",
    trigger: ["blur", "change"],
  },
};

const refRecharge = ref();

// 读卡
const refNfcPopup = ref();

const startReadCard = () => {
  console.log("开始读卡");
  refNfcPopup.value.reading();
};

const refTipsPopup = ref();
const openCamera = () => {
  refTipsPopup.value.open({
    title: "",
    content: "",
    autoClose: false,
  });
};

// 采集提示
const faceTipsList = [
  "面部光线均匀",
  "正对面部拍摄",
  "双侧耳朵可见",
  "双目眉可见",
  "口鼻清晰可见",
  "不戴口罩/眼镜",
  "不戴帽子",
];

// 开始人脸采集
const startScanFace = async () => {
  try {
    closeSubScreen();
    const localFaceFile = await asyncExecFunction(
      "baiduFaceRegistration",
       getDeviceConfig("face").params
    );
    openSubScreen();
    if (localFaceFile) {
      uni.showLoading({
        mask: true,
        title: "正在上传",
      });

      uploadFile({ url: localFaceFile }, () => {}, 0, "image").then(async (file) => {
        // 上传成功后进行更新后台信息和本地信息
        formData.faceUrl = file.url;
        updateHeadPortrait({
          customerInformationId: pagePam.id,
          faceUrl: file.url,
        }).then((res) => {
          uni.showLoading({
            mask: true,
            title: "同步完成",
          });
        });

        // 不管网络同步是否成功，本地数据必须更新

        const faceJson = JSON.stringify([
          {
            faceName: pagePam.id,
            faceUrl: file.url,
          },
        ]);

        try {
          const result = await asyncExecFunction("baiduFaceUrlRegistration", faceJson);
          // if (!Array.isArray(result)) throw new Error("批次人脸注册失败");
          console.log("[signFaceData ] 人脸数据注册完成", result);
          uni.hideLoading();
          uni.showToast({
            title: "采集成功",
            icon: "success",
          });
          refTipsPopup.value.close();
          // 刷新信息
          getPageData();
        } catch (error) {
          uni.showToast({
            title: "采集失败",
            icon: "error",
          });
          console.error("[signFaceData ] 人脸模采集注册失败 init", error);
          // 重新抛出异常
          throw error;
        }
      });
    }
    console.log("localFaceFile:>", localFaceFile);
  } catch (error) {
    openSubScreen();
    console.error(error);
    uni.showToast({
      title: "失败，请稍后重试",
      icon: "none",
    });
    uni.showModal({
      title: "失败",
      content: error?.message || "失败，请稍后重试",
    });
  }
};

// 保存
const confirm = async () => {
  try {
    const pam = { ...customerInfo.value, ...formData };
    const { data, success } = await customerEdit(pam);
    if (!success) throw new Error(data?.msg || "错误，请稍后重试");
    refResultPopup.value.open({
      title: "修改成功",
      content: "",
      closeInAfter: 10000,
      autoClose: true,
      type: "success",
    });
  } catch (error) {
    console.error(error);
    refResultPopup.value.open({
      title: "失败",
      content: error.data?.msg || "失败，请稍后重试",
      closeInAfter: 10000,
      autoClose: true,
      type: "fail",
    });
  }
};



// 地址选择器
const kuiTreepPicker = ref();
const treePickeConfig = reactive({
  treeData: [],
  action: "kingon-system/region/lazy-tree",
  param: {
    // parentId: 0,
    parentCode: "00",
  },
  enableLazy: false,
  props: {
    label: "title",
    children: "children",
    multiple: false,
    checkStrictly: false,
    nodes: false,
    // hasPath: false,
    postKey: "title",
  },
});
const onSubmitPicker = (val, treeData, stack) => {
  console.log("onSubmitPicker", { val, treeData, stack });
  // 获取栈数据
  formData.regionCodeName = stack.map((v) => v.title).join("");
  formData.regionCode = stack.map((v) => v.id).join("");
  formData.homeAddress = formData.regionCodeName;
};

const lazyFun = async (item, parenNode, index) => {
  console.log("lazyFun", { item, parenNode, index });
  // 自定义请求，并设置数据
  const reqConf = {
    url: "/kingon-system/region/lazy-tree",
    data: { parentCode: parenNode.id },
  };
  const { data } = await uni.$kui.request(reqConf);

  const treeData = data.map((item) => {
    if (!item.children) item.children = [];
    // 设置当前层级数据是否可选，（注意：设置成false，会往下触发）
    item.canSelect = true;
    // user 这个控制是否显示右边的右箭头按钮显示，<i v-if="!item.user"
    item.user = item.hasChildren === false ? true : false;
    return item;
  });
  parenNode.children = treeData;
};

const openSheet = async () => {
  try {
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    // 请求数据
    const reqConf = {
      url: treePickeConfig.action,
      data: treePickeConfig.param || {},
      header: treePickeConfig.header,
    };

    const { data } = await uni.$kui.request(reqConf);

    // 处理请求数据
    const treeData = data.map((item) => {
      if (!item.children) item.children = [];
      // 一般树形接口
      item.canSelect = item.hasChildren == false ? false : true;
      return item;
    });
    treePickeConfig.treeData = treeData;
    kuiTreepPicker.value.open({ props: treePickeConfig.props });
    uni.hideLoading();
  } catch (error) {
    uni.hideLoading();
    console.error(error);
  }
};
</script>
<style lang="scss" scoped>
.content {
  ::v-deep .u-search__content__icon {
    display: none;
  }
  .confirm-btn {
    ::v-deep .u-button {
      padding: 10rpx 30rpx;
      border-radius: 4rpx;
    }
  }
}


// kui 一些组件的宽屏样式修改
::v-deep .kui-treep-picker {
  .u-popup__content {
    max-width: 54vw;
    margin: auto;
    margin-bottom: 5vh;
    border-radius: 0.3125rem;
  }
  .region-container {
    > .title {
      font-size: 10rpx;
      padding: 10rpx;
      .close,
      .close2 {
        width: 12rpx;
        height: 12rpx;
      }
    }

    .header {
      top: 32rpx;
      .title {
        font-size: 10rpx;
        padding: 10rpx;
        height: 12rpx;
        line-height: 12rpx;
      }
      .iconclass {
        font-size: 10rpx;
      }
    }

    .container-list {
      .common {
        .content {
          font-size: 10rpx;
          padding: 10rpx;
          height: 15rpx;
          .list-item {
            display: block;
            .checkbox {
              .iconfont {
                font-size: 15rpx;

                &.icon-selected {
                  font-size: 15rpx !important;
                }
              }
            }
          }
          .lable-text {
            font-size: 10rpx;
            width: fit-content;
            margin-left: 10rpx;
          }

          .right {
            .iconclass {
              font-size: 12rpx;
            }
          }
        }
      }
    }
  }
  .btn.box_sizing {
    position: sticky;
    bottom: 0;
  }
}
</style>
